package innersort.merge;

import innersort.speed.SortStrategy;

import java.util.Arrays;

/**
 * @ author : HyoJoo-W
 * @ createDate : 2021-06-03 21:05
 * @ Description :
 */
public class MergeSort implements SortStrategy
{
    public static void main(String[] args)
    {
        int[] array = {8, 4, 5, 7, 1, 3, 6, 2};
        int[] temp = new int[array.length];
        mergeSort(array, 0, array.length - 1, temp);

        System.out.println("归并排序后的序列为:" + Arrays.toString(array));

    }

    @Override
    public void sort(int[] array)
    {
        int[] temp = new int[array.length];
        mergeSort(array, 0, array.length - 1, temp);
    }

    private static void mergeSort(int[] array, int left, int right, int[] temp)
    {
        if (left < right)
        {
            int mid = (left + right) / 2;
            //左递归分解
            mergeSort(array, left, mid, temp);
            //右递归分解
            mergeSort(array, mid + 1, right, temp);
            //合并
            merge(array, left, mid, right, temp);
        }
    }

    //合并
    private static void merge(int[] array, int left, int mid, int right, int[] temp)
    {
        int i = left;
        int j = mid + 1;
        int t = 0;//temp的索引指针

        //1. 将左右两边的有序数据按规则放入temp,直到左右两边的有序序列有一边处理结束
        while (i <= mid && j <= right)
        {
            if (array[i] <= array[j])
            {
                temp[t] = array[i];
                t++;
                i++;
            }
            else
            {
                temp[t] = array[j];
                t++;
                j++;
            }
        }


        //2. 将有剩余一边的数据全部放入temp
        while (i <= mid)
        {
            //左序列未处理结束
            temp[t++] = array[i++];
        }
        while (j <= right)
        {
            temp[t++] = array[j++];
        }

        //3. 将temp拷贝到array
        t = 0;
        int tempLeft = left;
        while (tempLeft <= right)
        {
            array[tempLeft++] = temp[t++];
        }
    }
}
